Skip to content

[CodeQuality] Reuse local stub variable when property used 2+ times in single method#702

Merged
TomasVotruba merged 1 commit into
mainfrom
reuse-stub-variable-on-multiple-uses
Jun 30, 2026
Merged

[CodeQuality] Reuse local stub variable when property used 2+ times in single method#702
TomasVotruba merged 1 commit into
mainfrom
reuse-stub-variable-on-multiple-uses

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Why

InlineStubPropertyToCreateStubMethodCallRector inlined $this->createStub(...) at every property fetch. When a stub property is used 2+ times in a single method, that produced multiple distinct stub instances — breaking identity checks like spl_object_id($this->formatter).

What

Per-method handling in refactorClassMethod():

  • 1 use in a method → inline directly (unchanged).
  • 2+ uses in a method → declare a local variable assigned to $this->createStub(...) above the first use, then reuse the variable.

Variable name via resolveVariableName(): formatter$formatterStub; a name already ending in Stub is kept as-is (someStub$someStub).

Before

public function testAnother()
{
    $handler = new FileLogHandler($this->createStub(FormatterInterface::class));
    $this->assertSame(spl_object_id($this->createStub(FormatterInterface::class)), spl_object_id($handler->getFormatter()));
}

After

public function testAnother()
{
    $formatterStub = $this->createStub(FormatterInterface::class);
    $handler = new FileLogHandler($formatterStub);
    $this->assertSame(spl_object_id($formatterStub), spl_object_id($handler->getFormatter()));
}

Only Stub properties are touched; MockObject (createMock) is left untouched.

Tests

  • Updated inline_used_in_calls.php.inc (2 uses → reuses local var).
  • Added reuse_variable_on_multiple_uses.php.inc.

ECS, PHPStan, Rector, and the rule tests all pass.

…n single method on InlineStubPropertyToCreateStubMethodCallRector
@TomasVotruba TomasVotruba merged commit 63a8471 into main Jun 30, 2026
8 checks passed
@TomasVotruba TomasVotruba deleted the reuse-stub-variable-on-multiple-uses branch June 30, 2026 21:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant